package com.bonc.excel.utils;

import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * @Description
 * @Author wujing
 */
public class LocalDateTimeUtils {

    //支持yyyy-MM-dd yyyy-MM-dd HH yyyy-MM-dd HH:mm yyyy-MM-dd HH:mm:ss
    public static final DateTimeFormatter FORMATTER;
    static {
        FORMATTER  =  new DateTimeFormatterBuilder()
                .appendPattern("yyyy-MM-dd[ [HH][:mm][:ss]]")
                .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
                .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
                .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
                .toFormatter();
    }



    /**
     *  LocalDateTime 转 Date
     * @param ldt LocalDateTime
     * @return Date
     */
    public static Date localDateTimeToDate(LocalDateTime ldt){
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = ldt.atZone(zoneId);
        return Date.from(zdt.toInstant());
    }

    /**
     * Date 转 LocalDateTime
     * @param date Date
     * @return LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date){
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * String 转 LocalDateTime
     * @param str String
     * @return LocalDateTime
     */
    public static LocalDateTime stringToLocalDateTime(String str,String pattern){
        if(StringUtils.isBlank(pattern)){
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(str,dateTimeFormatter);
    }

    /**
     * LocalDateTime 转 String
     * @param dt LocalDateTime
     * @return String
     */
    public static String localDateTimeToString(LocalDateTime dt,String pattern){
        if(StringUtils.isBlank(pattern)){
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        return dt.format(DateTimeFormatter.ofPattern(pattern));
    }

}
